package com.example.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.ProjectInfoMapper;
import com.example.dao.UxJbcardMapper;
import com.example.dao.UxenglstMapper;
import com.example.dao.UxpmStckMapper;
import com.example.dao.UxtpMapper;
import com.example.dao.UxmadsMapper;
import com.example.entity.JOBCard;
import com.example.entity.JobcardWeIdListST;
import com.example.entity.PartMaterialDetail;
import com.example.entity.ProjectShell;
import com.example.entity.RequiredMaterialDetail;
import com.example.entity.SchedulePlanEngineering;
import com.example.entity.SurplusMaterial;
import com.example.exchange.MapUtils;
import com.example.exchange.ServiceUtil;
import com.example.exchange.XMLHeaderConstants;
import com.example.util.XMLResUtil;
import com.example.service.AutoJobcArdServer;


import com.example.exchange.UnifierWebServicesUfbs;

@Service
public class AutoJobcArdSTServerImpl extends Util implements AutoJobcArdServer {

	@Autowired
	private UxenglstMapper uxenglstMapper;
	@Autowired
	private UxpmStckMapper uxpmStckMapper;
	@Autowired
	private UxJbcardMapper uxJbcardMapper;
	@Autowired
	private ProjectInfoMapper projectInfoMapper;
	@Autowired
	private UxtpMapper uxtpMapper;
	@Autowired
	private UxmadsMapper uxmadsMapper;

	/**

	 * 自动同步 jobcard 物料缺失

	 *

	 * @throws IOException

	 */
	public void auto_synchro_UXMMT() throws IOException {

		List<Map<String, String>> list = uxJbcardMapper.select_Jbcard_Material_Part(); // 查询出构件中的零件在即时库存中为0的

		if (list.size() != 0) {
			uxJbcardMapper.delete_uxdram();
			uxJbcardMapper.delete_uxdram_PERM();

			Set<String> DrawingSet = new HashSet<String>();

			List<Map<String, String>> list2 = uxJbcardMapper.select_Jbcard_Material_CUT();// 查询出目前下切缺母材的 需产生的零件编码

			for (Map<String, String> index : list) {
				for (Map<String, String> index2 : list2) {
					if (index.get("PART_NO").equals(index2.get("MATERIAL_CODE"))) {
						DrawingSet.add(index2.get("DRAWING_NO"));// 筛入缺母材，相关MTO

						DrawingSet.add(index2.get("DRAWING_NO"));// 筛入缺母材，相关MTO

						index.put("JOBCard_No_1", index2.get("DRAWING_NO"));
						index.put("Rev_1", index2.get("REV"));
						if (index2.get("MATERIAL_STATUS").equals("NOK")) {
							index.put("Material_Sort", "bulk"); // 缺母材

						} else {
							index.put("Material_Sort", "part");
						}
						break;
					}

				}

			}
			List<Map<String, String>> listMto = uxJbcardMapper.select_Jbcard_Material_MTO(DrawingSet);

			for (Map<String, String> index : list) {
				for (Map<String, String> index2 : listMto) {
					String DRAWING_NO = index.get("JOBCard_No_1");
					String REV = index.get("Rev_1");
					if (index2.get("DRAWING_NO").equals(DRAWING_NO) && index2.get("REV").equals(REV)) {
						index.put("MATERIAL_NAME", index2.get("MATERIAL_NAME"));
						index.put("MTO_NO", index2.get("MTO_NO"));
						index.put("TECHNICAL_REQUIREMENT", index2.get("TECHNICAL_REQUIREMENT"));
						System.err.println(index);
					}
				}
			}
			Integer id = uxJbcardMapper.select_uxdram_MaxID();
			if (id == null) {
				id = 1;
			} else {
				id++;
			}
			for (int i = 0; i < list.size() / 500 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交

				List<Map<String, String>> index = new ArrayList<Map<String, String>>();
				if ((i + 1) * 500 > list.size())
					index = list.subList(i * 500, list.size());
				if ((i + 1) * 500 <= list.size())
					index = list.subList(i * 500, (i + 1) * 500);
				if (index.size() != 0) {
					uxJbcardMapper.INSERT_uxdram(list, id);
					uxJbcardMapper.INSERT_uxdram_PERM(list, id);
					id = id + index.size();
				}
			}
		}

	}

	/**

	 *

	 * 自动为优先级中的构件进行备料，如构件的套料未进行下发则也为其进行备料

	 *

	 * @throws IOException

	 */
	public void auto_IssuedJobcardST() throws IOException {
		JOBCard jobcard = new JOBCard();

		List<Map<String, String>> projectInfoMaps = projectInfoMapper.select_ProjectID_Number(); // 查找出所有项目


		for (Map<String, String> projectInfoMap : projectInfoMaps) { // 遍历项目


			Object object = projectInfoMap.get("PID");
			int projectId = Integer.parseInt(String.valueOf(object));
			List<Integer> MaterPri1s = uxJbcardMapper.selectUXMPP_MaterPri(projectId, "ST"); // 查出第一序列备料优先级

			boolean is = false; // 用于判断是否开启后续大组的备料

			for (Integer MaterPri1 : MaterPri1s) { // 循环第一序列

				List<Map<String, String>> datas = uxJbcardMapper
						.selectjobcard_MaterialPreparationST_fabrication(projectId, MaterPri1);// 查出所有未下发的Jobacrd

				for (Map<String, String> data : datas) {// 遍历序列中的备料单


					if (data.get("DRAWING_NO") == null || data.get("JOBC_RECORD_NO") == null) {
						// 无图纸信息或无预Jobcard 则结束此序列备料

						if (is == false) {
							is = true;
						}

						continue;
					}

					if (data.get("MATERIAL_STATUS").equals("NOK")) {// 如果未备料

						// 查询构件所属零件

						List<Map<String, String>> parts = uxJbcardMapper
								.selectjobcard_MaterialPreparationST_Fabrication_Part(projectId, data.get("DRAWING_NO"),
										data.get("REV"));

						List<String> partNos = new ArrayList<String>();

						for (Map<String, String> index : parts) {
							Object NO = index.get("NO"); // BigDecimal 要先转为Object

							int projectNO = Integer.parseInt(String.valueOf(NO));
							if (projectNO > 0) { // 如果齐全则往下备料

								partNos.add(index.get("MATERIAL_CODE"));// 收集无库存的零件编码

							}
						}

						if (partNos.size() > 0) {// 零件库存不满足

							List<Map<String, String>> nestings = uxJbcardMapper
									.selectjobcard_NestingST_PartNo(projectId, partNos); // 获得未备料的套料jobcard

							for (Map<String, String> nesting : nestings) {
								boolean bulkis = true;
								List<Map<String, String>> bulks =null;

								bulks = uxJbcardMapper
										.selectjobcard_MaterialPreparationST_Nesting_remnant(projectId,
												nesting.get("DRAWING_NO"), nesting.get("REV")); // 查出 是否备料齐全

								if(bulks.isEmpty()) {//如果套料图使用的是余料的话则直接满足

									bulks = uxJbcardMapper
											.selectjobcard_MaterialPreparationST_Nesting_bulk(projectId,
													nesting.get("DRAWING_NO"), nesting.get("REV")); // 查出 是否备料齐全

									for (Map<String, String> index : bulks) {
										Object NO = index.get("NO"); // BigDecimal 要先转为Object

										int projectNO = Integer.parseInt(String.valueOf(NO));
										if (projectNO > 0) { // 如果齐全则往下备料

											if (is == false) {
												is = true;
											}
											bulkis = false;
											continue;
										}
									}
								}


								if (bulkis) { // 为构件相关的套料图进行备料

									jobcard.setRecord_no(nesting.get("JOBC_RECORD_NO"));
									String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, JOBCard.class,
											MapUtils.java2Map(jobcard));
									xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
									UnifierWebServicesUfbs UnifierWebServicesUDF = new UnifierWebServicesUfbs();

									String oprionsXml = " <options><WFCurrentStepName>Discipline Engineer Check</WFCurrentStepName>"
											+ "<WFActionName>Material Preparation Completed</WFActionName></options>";
									// WFCurrentStepName 当前步骤名称 WFActionName执行的操作名称


									String mgs = this.processResult(UnifierWebServicesUDF.updateBPRecordV2(
											projectInfoMap.get("PROJECTNUMBER"), "JOBCard List", xml, oprionsXml));
									System.err.println(mgs);
									if (mgs.equals("Success")) { // 工作流推送成功则进行物料锁定

										uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(data.get("JOBC_RECORD_NO")); // 修改jobcard状态

										if(bulks!=null) {
											uxpmStckMapper.updateUxpmStckTotal(bulks);// 锁定库存

										}
									} else if (mgs.equals("Failed, WFCurrentStepName is not correct.")) {
										uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(data.get("JOBC_RECORD_NO")); // 修改jobcard状态

										if(bulks!=null) {
											uxpmStckMapper.updateUxpmStckTotal(bulks);// 锁定库存

										}
									} else {
										if (is == false) {
											is = true;
										}
										continue;
									}
								}

							}
						} else {//如果构件的零件满足则对构件进行备料并推动工作流节点


							jobcard.setRecord_no(data.get("JOBC_RECORD_NO"));
							String xml = ServiceUtil.createXML(false, XMLHeaderConstants.BP, JOBCard.class,
									MapUtils.java2Map(jobcard));
							xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
							UnifierWebServicesUfbs UnifierWebServicesUDF = new UnifierWebServicesUfbs();

							String oprionsXml = " <options><WFCurrentStepName>Discipline Engineer Check</WFCurrentStepName>"
									+ "<WFActionName>Material Preparation Completed</WFActionName></options>";
							// WFCurrentStepName 当前步骤名称 WFActionName执行的操作名称


							String mgs = this.processResult(UnifierWebServicesUDF.updateBPRecordV2(
									projectInfoMap.get("PROJECTNUMBER"), "JOBCard List", xml, oprionsXml));
							System.err.println(mgs);
							if (mgs.equals("Success")) { // 工作流推送成功则进行物料锁定

								uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(data.get("JOBC_RECORD_NO")); // 修改jobcard状态

								uxpmStckMapper.updateUxpmStckTotal(parts);// 锁定库存

							} else if (mgs.equals("Failed, WFCurrentStepName is not correct.")) {
								uxJbcardMapper.update_UXJBCARD_MATERIAL_STATUS2(data.get("JOBC_RECORD_NO")); // 修改jobcard状态

								uxpmStckMapper.updateUxpmStckTotal(parts);// 锁定库存

							} else {
								if (is == false) {
									is = true;
								}
								continue; // 结束此序列的备料（第一序列）

							}
						}


					}

				}

				if (is) {// 如果次序列中有构件未成功备料 未生成备料单则停止别的 第一序列备料

					break;
				}
			}
		}
	}

	/**

	 * 自动生成 结构专业下切 组队Jobcard

	 *

	 * @throws IOException

	 */
	public void auto_GenerateJobcard_ST() throws IOException {

		List<SchedulePlanEngineering> list = uxenglstMapper.selectUxenglstJobcArd();

		for (SchedulePlanEngineering index : list) {
			// logger.info("抓取到一条符合条件的图纸：" + index.getDrawing_No());

			// 2-创建一个JOBCard空记录

			JOBCard jobcard = new JOBCard();
			// 3-取BP自带项目信息CODE & NAME

			// 原DRAW包括项目信息，后取消两要素，WEBSERVICE 方法直接输入Project_ID

			ProjectShell project = projectInfoMapper.select_ProjectShellDetail(index.getProject_id());
			// 赋值JB 编号，对应合同号，业主

			jobcard.setContract_No(project.getContractNo()); // 合同号

			jobcard.setClient(project.getClient());// 客户

			// 赋值JB 模块号，专业，工序，工作车间 ,工作包号

			jobcard.setWork_Package_No(index.getWork_Package_No());
			jobcard.setModule_Number(index.getModule_Name());
			jobcard.setDiscipline(index.getDiscipline());
			jobcard.setWork_Location(jobcard.getDiscipline() + " Workshop");
			// 更新图纸及版本信息

			jobcard.setDrawing_No(index.getDrawing_No());
			jobcard.setDrawing_Name(jobcard.getDrawing_No());
			jobcard.setDrawing_Version(index.getRev());

			if (index.getDrawing_Category().equals("nesting")) {
				// 查询物料库存即时库存数据

				// 根据draw（套料图含图纸编号和版本）找到母材，关联即时库存表进而查询得到

				List<RequiredMaterialDetail> requiredMaterials = new ArrayList<RequiredMaterialDetail>();
				List<SurplusMaterial> surplusMaterials = new ArrayList<SurplusMaterial>();

				surplusMaterials = uxpmStckMapper.selectUxpmstck_Drawing_No_Remnant(index.getDrawing_No(),
						index.getRev(), project.getProjectObjectid()); // 查询套料图关联的余料

				if (surplusMaterials.size() > 0) {// 如果没有余料则 查询母材

					jobcard.setMaterial_Progress("100%");
					jobcard.setMaterial_Status("Preparing");
				} else {
					requiredMaterials = uxpmStckMapper.selectUxpmstck_Drawing_No_bulk(index.getDrawing_No(),
							index.getRev(), project.getProjectObjectid()); // 查询母材

					// 根据上述数量计算当前材料 准备进展%

					jobcard.setMaterial_Progress("0%");
					jobcard.setMaterial_Status("Preparing");
				}

				// jobcard 查询产生零件

				List<PartMaterialDetail> partMaterialDetails = uxpmStckMapper
						.select_UxmatepPartList(index.getDrawing_No(), index.getRev(), project.getProjectObjectid());

				jobcard.setJOBCard_No(index.getModule_Name() + "-" + index.getWork_Package_No() + "-ST" + "-MAC");

				jobcard.setWorking_Procedure("cut");// 为jobcard 选定 工序


				insertJobcArdST(project.getProjectNumber(), index, jobcard, partMaterialDetails, requiredMaterials,
						null, surplusMaterials, null);// 创建JobcArd


			} else if (index.getDrawing_Category().equals("fabrication")) { // 图纸类型是 预制图类型的话 构架图


				// 预制图同时创建 组队与焊接jobcArd

				boolean is = false;
				List<Map<String, String>> datas = uxpmStckMapper.select_Uxmateptlist(index.getDrawing_No(),
						index.getRev(), project.getProjectObjectid());
				List<JobcardWeIdListST> dataList = uxJbcardMapper.selectWeIdListST(jobcard.getDrawing_No(),
						jobcard.getDrawing_Version(), index.getProject_id());


				if (datas.size() > 0) {
					for (Map<String, String> data : datas) { // 遍历构件所需的零件

						is = this.partis(data.get("PART_NAME"), data.get("STRUCTURE_TYPE"));

						if (is) {// 判断是否需要预制

							// 生成组队 JObcard

							jobcard.setJOBCard_No( index.getModule_Name() + "-" +
									index.getWork_Package_No() + "-ST-" + "F&U");
							insertJobcArdFabricationST(project.getProjectNumber(), "fitup", index,
									jobcard, dataList);
							// 生成焊接 JObcard

							jobcard.setJOBCard_No(
									index.getModule_Name() + "-" + index.getWork_Package_No() + "-ST-" + "V/S");
							insertJobcArdFabricationST(project.getProjectNumber(), "weld", index, jobcard, dataList);
							break;
						}
					}
					if (is == false) {

						jobcard.setJOBCard_No(
								index.getModule_Name() + "-" + index.getWork_Package_No() + "-ST-" + "ERE");
						insertJobcArdFabricationST(project.getProjectNumber(), "install", index, jobcard, dataList);

					}

				}
				// 将生成JObc ard 的 图纸状态改变为已生成JObcard

				uxenglstMapper.updateTriggerStatusV2(index.getProject_id(), index.getRecord_no());
			}

		}
	}

	/**

	 * 为结构专业Shop图自动生成Jobcard

	 *

	 * @throws IOException

	 */
	public void auto_GenerateJobcardShop_ST() throws IOException {

		List<SchedulePlanEngineering> list = uxenglstMapper.selectUxenglstJobcArdST_Shop();

		List<SchedulePlanEngineering> shoplist = new ArrayList<SchedulePlanEngineering>();

		Iterator<SchedulePlanEngineering> it = list.iterator();
		while (it.hasNext()) {
			SchedulePlanEngineering index = it.next();
			if (index.getDrawing_Category().equals("shop")) {
				boolean is = true;
				for (int i = 0; i < shoplist.size(); i++) {
					Object object1 = index.getJobcard_install_No();
					Object object2 = shoplist.get(i).getJobcard_install_No();
					if (object1.equals(object2)) {
						is = false;
					}
				}
				if (is) {
					shoplist.add(index);
				}
				it.remove();
			}
		}
		list.addAll(shoplist);
		for (SchedulePlanEngineering index : list) {
			// logger.info("抓取到一条符合条件的图纸：" + index.getDrawing_No());

			// 2-创建一个JOBCard空记录

			JOBCard jobcard = new JOBCard();
			// 3-取BP自带项目信息CODE & NAME

			// 原DRAW包括项目信息，后取消两要素，WEBSERVICE 方法直接输入Project_ID

			ProjectShell project = projectInfoMapper.select_ProjectShellDetail(index.getProject_id());
			// 赋值JB 编号，对应合同号，业主

			jobcard.setContract_No(project.getContractNo()); // 合同号

			jobcard.setClient(project.getClient());// 客户

			// 赋值JB 模块号，专业，工序，工作车间 ,工作包号

			jobcard.setWork_Package_No(index.getWork_Package_No());
			jobcard.setModule_Number(index.getModule_Name());
			jobcard.setDiscipline(index.getDiscipline());
			jobcard.setWork_Location(jobcard.getDiscipline() + " Workshop");
			// 更新图纸及版本信息

			jobcard.setDrawing_No(index.getDrawing_No());
			jobcard.setDrawing_Name(jobcard.getDrawing_No());
			jobcard.setDrawing_Version(index.getRev());
			// 根据jobcard的图纸代码规则从获取JOBCard-Nesting图纸匹配的作业活动

			JOBCard rs = uxJbcardMapper.getP6ScheduleL5Activity(jobcard); // 目前计划与图纸未关联上

			// logger.info("查询图纸对应的库存信息 ...");

			// 下切，组对和焊接分别对应三种不同的情况

			if (rs != null) {
				jobcard.setUuu_activity_code(rs.getUuu_activity_code());
				jobcard.setUuu_activity_name(rs.getUuu_activity_name());
				jobcard.setPlan_Started(rs.getPlan_Started());
				jobcard.setPlan_Finish(rs.getPlan_Finish());
			}

			int materialplans = 0;
			int materialcurrents = 0;

			int num = uxenglstMapper.select_uxenglst_Jobcard_install_No(index.getDiscipline(), index.getProject_id(),
					index.getJobcard_install_No(), index.getRev());
			int activeNum = uxenglstMapper.select_uxenglst_Jobcard_install_No_Active(index.getDiscipline(),
					index.getProject_id(), index.getJobcard_install_No(), index.getRev());
			if (num == activeNum) {
				jobcard.setJOBCard_No(index.getJobcard_install_No());
				List<PartMaterialDetail> listMaterial = uxpmStckMapper.selectUxpmstck_Drawing_No_Fabrication(
						index.getDrawing_No(), index.getRev(), Integer.valueOf(project.getProjectNumber()));

				for (PartMaterialDetail entity : listMaterial) {
					// 赋值需求数和实际数

					materialplans += entity.getRequire_QTY();
					materialcurrents += entity.getActual_QTY();
				}
				// 根据上述数量计算当前材料 准备进展%

				try {
					jobcard.setMaterial_Progress((materialcurrents / materialplans) * 100 + "%");
				} catch (Exception e) {
					jobcard.setMaterial_Progress("0%");
				}
				if (materialplans < materialcurrents || materialplans == materialcurrents) {
					jobcard.setMaterial_Status("isReady");
				} else {
					jobcard.setMaterial_Status("Preparing");
				}

				jobcard.setWorking_Procedure("install");// 为jobcard 选定 工序 安装工序

				jobcard.setJOBCard_No(index.getModule_Name() + "-" + index.getWork_Package_No() + "-ST-" + "ERE");
				insertJobcArdST(project.getProjectNumber(), index, jobcard, listMaterial, null, null, null, null);// 插入创建jobcArd

				uxenglstMapper.updateTriggerStatus(index.getProject_id(), index.getDiscipline(),
						index.getJobcard_install_No());
				// session.commit();

				// break;

			}

		}
	}

}